﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 目录上传/撤销/查询服务
    /// </summary>
    public class CatalogQueryService
    {
        /// <summary>
        /// 3301 目录上传对照
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> CatalogCompUp(FsiRequestHeader<InputCatalogCompUp> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            List<DataCatalogCompUp> list = new List<DataCatalogCompUp>();
            list = fsiRequest.Input.data;
            string fixmedins_code = fsiRequest.fixmedins_code;
            if (string.IsNullOrEmpty(fixmedins_code) || list.Count == 0)
            {
                throw new Exception("参数校验失败：传入的机构代码|上传商品数组为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (var conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                await conn.OpenAsync();
                string error = "";
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.Transaction = transaction;
                        foreach (var item in list)
                        {
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_catalogcompup  VALUES (@fixmedins_code, @fixmedins_hilist_id, @fixmedins_hilist_name,@list_type, @med_list_codg, @begndate, @enddate, @aprvno, @dosform, @exct_cont, @item_cont, @prcunt, @spec, @pacspec, @memo, @scdz, @prdr_name,@create_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_id", item.fixmedins_hilist_id);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_name", item.fixmedins_hilist_name);
                                cmd.Parameters.AddWithValue("@list_type", item.list_type);
                                cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                cmd.Parameters.AddWithValue("@begndate", item.begndate);
                                cmd.Parameters.AddWithValue("@enddate", item.enddate);
                                cmd.Parameters.AddWithValue("@aprvno", item.aprvno);
                                cmd.Parameters.AddWithValue("@dosform", item.dosform);
                                cmd.Parameters.AddWithValue("@exct_cont", item.exct_cont);
                                cmd.Parameters.AddWithValue("@item_cont", item.item_cont);
                                cmd.Parameters.AddWithValue("@prcunt", item.prcunt);
                                cmd.Parameters.AddWithValue("@spec", item.spec);
                                cmd.Parameters.AddWithValue("@memo", item.memo);
                                cmd.Parameters.AddWithValue("@scdz", item.scdz);
                                cmd.Parameters.AddWithValue("@prdr_name", item.prdr_name);
                                cmd.Parameters.AddWithValue("@create_time", createTime);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                error = error + $"【{item.fixmedins_hilist_name}/{item.spec}/{item.prcunt}/{item.prdr_name}/{item.aprvno}】上传出错：" + ex.Message + "|";
                            }
                            cmd.Parameters.Clear();
                        }
                        if (error != "")
                        {
                            transaction.Rollback();
                            throw new Exception(error);

                        }
                        else
                        {
                            transaction.Commit();
                            return true;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 3302 目录上传撤销
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> DeleteCatalogCompAudited(FsiRequestHeader<InputDeleteCatalogCompAudited> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
            string fixmedins_hilist_id = fsiRequest.Input.data.fixmedins_hilist_id;
            string med_list_codg = fsiRequest.Input.data.med_list_codg;

            if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(fixmedins_hilist_id) || string.IsNullOrEmpty(med_list_codg))
            {
                throw new Exception("参数校验失败：传入的机构代码|医疗机构内部编码|医保国家编码为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (var conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                await conn.OpenAsync();
                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id ";
                    cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                    cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        if (dt.Rows.Count < 1)
                        {
                            throw new Exception($"查询商品上传记录表失败：根据传入的机构代码【{fixmedins_code}】、医疗机构内部编码【{fixmedins_hilist_id}】未找商品已上传记录！");
                        }
                        else
                        {
                            cmd.Parameters.Clear();
                            cmd.CommandText = "delete from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id  ";
                            cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                            await cmd.ExecuteNonQueryAsync();
                            return true;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 1317 查询定点医药机构目录上传记录
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputQueryMedListMapByPage> QueryMedListMapByPage(FsiRequestHeader<InputQueryMedListMapByPageRequest> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
            string medins_list_codg = fsiRequest.Input.data.medins_list_codg;//定点医药机构目录编号
            string medins_list_name = fsiRequest.Input.data.medins_list_name;//定点医药机构目录名称
            string med_list_codg = fsiRequest.Input.data.med_list_codg;//医疗目录编码
            int page_num = fsiRequest.Input.data.page_num;//当前页
            int page_size = fsiRequest.Input.data.page_size;//本页数据
            if (string.IsNullOrEmpty(fixmedins_code) || page_num == 0 || page_size == 0)
            {
                throw new Exception("参数校验失败：传入的机构代码|当前页码|当前页条数为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (var conn = new MySqlConnection(connectionString))
            {
                if (string.IsNullOrEmpty(medins_list_codg))
                {
                    medins_list_codg = "%";
                }
                if (string.IsNullOrEmpty(medins_list_name))
                {
                    medins_list_name = "%";
                }
                if (string.IsNullOrEmpty(med_list_codg))
                {
                    med_list_codg = "%";
                }
                int now_page = (page_num - 1) * page_size;
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                await conn.OpenAsync();
                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id like @medins_list_codg and fixmedins_hilist_name like @medins_list_name and med_list_codg like @med_list_codg limit @nowpage,@pagesize";
                    cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                    cmd.Parameters.AddWithValue("@medins_list_codg", "%" + medins_list_codg + "%");
                    cmd.Parameters.AddWithValue("@medins_list_name", "%" + medins_list_name + "%");
                    cmd.Parameters.AddWithValue("@med_list_codg", "%" + med_list_codg + "%");
                    cmd.Parameters.AddWithValue("@nowpage", now_page);
                    cmd.Parameters.AddWithValue("@pagesize", page_size);
                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                    {
                        DataTable dt = new DataTable();
                        List<DataQueryMedListMapByPage> dataList = new List<DataQueryMedListMapByPage>();
                        dt.Load(reader);
                        cmd.Parameters.Clear();
                        foreach (DataRow row in dt.Rows)
                        {
                            DataQueryMedListMapByPage item = new DataQueryMedListMapByPage
                            {
                                fixmedins_code = row["fixmedins_code"].ToString(),
                                medins_list_codg = row["fixmedins_hilist_id"].ToString(),
                                medins_list_name = row["fixmedins_hilist_name"].ToString(),
                                insu_admdvs = fsiRequest.mdtrtarea_admvs.ToString(),
                                list_type = row["list_type"].ToString(),
                                med_list_codg = row["med_list_codg"].ToString(),
                                begndate = row["begndate"].ToString(),
                                enddate = row["enddate"].ToString(),
                                aprvno = row["aprvno"].ToString(),
                                dosform = row["dosform"].ToString(),
                                exct_cont = row["exct_cont"].ToString(),
                                item_cont = row["item_cont"].ToString(),
                                prcunt = row["prcunt"].ToString(),
                                spec = row["spec"].ToString(),
                                pacspec = row["pacspec"].ToString(),
                                memo = row["memo"].ToString(),
                                updt_time = row["create_time"].ToString(),
                                crte_time = row["create_time"].ToString()
                            };
                            dataList.Add(item);
                        }
                        var output = new OutputQueryMedListMapByPage
                        {
                            data = dataList,
                            size = dt.Rows.Count,
                            startRow = 1,
                            endRow = dt.Rows.Count,
                            pageSize = page_size,
                            pageNum = page_num
                        };
                        return output;
                    }
                }
            }
        }
    }
}
